package com.gvitz.transaction.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.SpannableString;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.gvitz.transaction.R;
import com.gvitz.transaction.activities.MainActivity;
import com.gvitz.transaction.database.gvitzDB;
import com.gvitz.transaction.models.Client;

public class MapaFragment extends SherlockFragment
        implements OnMarkerClickListener, OnInfoWindowClickListener,LocationListener {	

    private GoogleMap mMap;
	private View view;
	private LocationManager locationManager;
	private static final long MIN_TIME = 400;
	private static final float MIN_DISTANCE = 1000;

	gvitzDB dbHelper= null;
	Context context = null;
	SharedPreferences prefs = null;
    Activity act = null;
    ArrayList<Client> mClientes = null;
    Map<Marker,Client> MCList =new HashMap<Marker, Client>();



    
	/** OnCreateView*/
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		 //revisar si la vista esta creada.
	    
			 if (view != null) {
				 ViewGroup parent = (ViewGroup) view.getParent();
				 if (parent != null)
					 parent.removeView(view);
			 	}
			
			 try {
				 view = inflater.inflate(R.layout.fragment_map, container, false);
			 		} catch (InflateException e) {
			 			/* map is already there, just return view as it is */
			 	}

			 setUpMapIfNeeded();			
			 context = getActivity();
			 act = getActivity();
			 
			 act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
	    
			//Mi posicion
			 prefs = getActivity().getSharedPreferences("preferencias",0);
	    
			 locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
	   		  	  
			 //Cell-ID and WiFi location updates.
			 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
			 
		return view;
	}




    /**Estado del mapa*/
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }
    
    /** Setea variables y agrega los puntos al mapa */
    private void setUpMap() {
    	        
    	//Mostrar zoom
        mMap.getUiSettings().setZoomControlsEnabled(true);
        
        // Boton centrar mapa y obtener mi posicion        
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
       
        //Agregar eventos al mapa
        addMarkersToMap();
        
        // Adaptador para la ventana emergente de un evento
        mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());

        // Set listeners for marker events.  See the bottom of this class for their behavior.
        mMap.setOnMarkerClickListener(this);
        mMap.setOnInfoWindowClickListener(this);

       }
    
    
   /** Agrega puntos al mapa */    
    private void addMarkersToMap() {
    	
    	//base de datos   	
    	dbHelper = new gvitzDB(getActivity().getApplicationContext());
    	mClientes = dbHelper.GetClients();

    	
    	//colores
    	float[] HSV = new float[3];  
    	
    	//marker
    	Marker marker = null;
    	
    	if (mClientes != null) {
    	 
		 for( int i=0; i < mClientes.size(); i++){
			 
			 Color.RGBToHSV(127,159,26,HSV);
		       marker = mMap.addMarker(new MarkerOptions()
		                .position(new LatLng(
		                		Double.parseDouble(mClientes.get(i).getLatitud())/1000000,
		                		Double.parseDouble(mClientes.get(i).getLongitud())/1000000))
		                .title(mClientes.get(i).getNombre())
		                .snippet(mClientes.get(i).getDireccion())
		                .icon(BitmapDescriptorFactory.defaultMarker(HSV[0])));

		      MCList.put(marker,mClientes.get(i));

	
		    }
    	}
		
    }
      
    /** Onclic del evento con efecto de movimiento */
    @Override
    public boolean onMarkerClick(final Marker marker) {

        
        return false;
    }

    /** Para abrir Perfil del Evento */
    @Override
    public void onInfoWindowClick(Marker marker) {
    	 
    	 Client c =MCList.get(marker);
			
    	    String TabOfFragmentP = ((MainActivity) getActivity()).getTabFragmentP();

			PaymentFragment fragmentP = (PaymentFragment) getActivity()
						.getSupportFragmentManager().findFragmentByTag(TabOfFragmentP);

				fragmentP.update_SL(c.getId_client());
                getSherlockActivity().getSupportActionBar().setSelectedNavigationItem(1);
 

    }
   
    /** Clase para customizar el cuadro con la informacion  */  
    class CustomInfoWindowAdapter implements InfoWindowAdapter {

    	private final View mWindow;

        CustomInfoWindowAdapter() {
            mWindow = getActivity().getLayoutInflater().inflate(R.layout.custom_info_window, null);
        }

        @Override
        public View getInfoWindow(Marker marker) {
            render(marker, mWindow);
            return mWindow;
        }


        private void render(Marker marker, View view) {
  
            
            //Titulo 

            String title = marker.getTitle();
            TextView titleUi = ((TextView) view.findViewById(R.id.title));
            
            if (title != null) {
                SpannableString titleText = new SpannableString(title);
                titleUi.setText(titleText);
            } else {
                titleUi.setText("");
            }

            // Resumen 
            
            String snippet = marker.getSnippet();
            TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
            
            if (snippet != null) {
                SpannableString snippetText = new SpannableString(snippet);
                snippetUi.setText(snippetText);
            } else {
                snippetUi.setText("");
            }
        }

		@Override
		public View getInfoContents(Marker marker) {
			//  Auto-generated method stub
			return null;
		}
    }

    /** Metodo para obtener mi posicion actual */
	@Override
	public void onLocationChanged(Location location) {		
		SharedPreferences.Editor editor = prefs.edit();
		 	 
		//agregar mi posicion a las preferencias	 
		 editor.putString("latitud",String.valueOf((int)(location.getLatitude()*1000000)));
		 editor.putString("longitud",String.valueOf((int)(location.getLongitude()*1000000)));
		 editor.commit();
		 
	       	 //centrar la camara en mi posicion actual
	   	     LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
		     CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 16);
		     mMap.animateCamera(cameraUpdate);
		     locationManager.removeUpdates(this);

	}

	@Override
	public void onProviderDisabled(String provider) {
		// Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// Auto-generated method stub
		
	}
		
    @Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}
       	
}
